﻿using CkSoftware.GroupMe.Sdk.Core;
using CkSoftware.GroupMe.Sdk.Core.Dao;
using CkSoftware.GroupMe.Sdk.Core.Exceptions;
using CkSoftware.GroupMe.Sdk.Messaging.Commands;
using Newtonsoft.Json;

namespace CkSoftware.GroupMe.Sdk.Messaging.Dao
{
	/// <summary>
	/// The parameters for the <see cref="GroupMessagesIndexCommand" />.
	/// </summary>
	public class GroupMessagesIndexParameters : IWebApiCommandParameters
	{
		/// <summary>
		/// Instantiates a new <see cref="GroupMessagesIndexParameters" /> object.
		/// </summary>
		/// <param name="groupId">The group id for which the messages should be loaded.</param>
		/// <param name="beforeId">The message-id of the oldest already loaded message (for scrolling backward).</param>
		/// <param name="sinceId">The message-id of the newest already loaded message (for scrolling forward).</param>
		public GroupMessagesIndexParameters(string groupId, string beforeId = null, string sinceId = null)
		{
			bool hasBeforeId = !string.IsNullOrEmpty(beforeId);
			bool hasSinceId = !string.IsNullOrEmpty(sinceId);

			if (hasBeforeId && hasSinceId)
			{
				throw new GroupMeException(new MetaData
				{
					Code = 500,
					Errors = new[] {"Only a beforeId or a sinceId can be given, not both."}
				});
			}

			if (string.IsNullOrEmpty(groupId))
			{
				throw new GroupMeException(new MetaData {Code = 500, Errors = new[] {"There must be a group id defined."}});
			}

			GroupId = groupId;
			BeforeId = beforeId;
			SinceId = sinceId;
		}

		/// <summary>
		/// The message-id of the oldest already loaded message (for scrolling backward).
		/// </summary>
		[JsonProperty(PropertyName = "before_id")]
		public string BeforeId { get; set; }

		/// <summary>
		/// The group id for which the messages should be loaded.
		/// </summary>
		[JsonIgnore]
		public string GroupId { get; set; }

		/// <summary>
		/// The message-id of the newest already loaded message (for scrolling forward).
		/// </summary>
		[JsonProperty(PropertyName = "since_id")]
		public string SinceId { get; set; }
	}
}